import openpyxl


def replace_text_in_sheet(sheet, replacements):
    """Replace text in all cells of a given sheet according to the replacements dictionary."""
    for row in sheet.iter_rows():
        for cell in row:
            if cell.value is not None and isinstance(cell.value, str):
                for old_text, new_text in replacements.items():
                    if old_text in cell.value:
                        cell.value = cell.value.replace(old_text, new_text)


def replace_text_in_workbook(workbook, replacements):
    """Replace text throughout the entire workbook according to the replacements dictionary."""
    for sheet in workbook.worksheets:
        replace_text_in_sheet(sheet, replacements)


def fix(input_file, replacements):
    """Main function to load a workbook, perform text replacements, and save the workbook."""
    # Load the workbook
    workbook = openpyxl.load_workbook(input_file)

    # Replace text in the workbook
    replace_text_in_workbook(workbook, replacements)

    # Save the modified workbook (overwriting the original)
    workbook.save(input_file)


if __name__ == "__main__":
    input_file = 'target/利润分析表-+++++项目.xlsx'  # 使用绝对路径或相对路径
    replacements = {
        '${项目名称}': '郑州华电富士康综合能源',
        '${小写金额}': '2123.50',
        '${纳税人电话}': '',
        '${客户名称}': '王一然',
        '${交付经理}': '利息也',
        '${省解决方案经理}': '王明阳',
        '${采购经理}': '李清照',
    }

    fix(input_file, replacements)
